package com.dhecp.project.storage.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.project.business.domain.ProductActive;
import com.dhecp.project.business.domain.ProductActiveComponent;
import com.dhecp.project.business.mapper.ProductActiveMapper;
import com.dhecp.project.common.domain.ModuleNID;
import com.dhecp.project.common.domain.ModuleNidAndBid;
import com.dhecp.project.common.domain.RecordCheck;
import com.dhecp.project.common.domain.UpdateDeleted;
import com.dhecp.project.common.domain.UpdateFlow;
import com.dhecp.project.common.mapper.ModuleNidAndBidMapper;
import com.dhecp.project.common.service.UpdateLogService;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.finance.domain.AccountCountForCompany;
import com.dhecp.project.finance.mapper.AccountCountForCompanyMapper;
import com.dhecp.project.hr.domain.OperateCompanyApply;
import com.dhecp.project.hr.domain.OperateCompanyRoute;
import com.dhecp.project.hr.mapper.OperateCompanyApplyMapper;
import com.dhecp.project.hr.mapper.OperateCompanyRouteMapper;
import com.dhecp.project.purchase.domain.PurchaseAddress;
import com.dhecp.project.purchase.domain.PurchasePlan;
import com.dhecp.project.purchase.domain.PurchasePlanSon;
import com.dhecp.project.purchase.mapper.PurchaseAddressMapper;
import com.dhecp.project.purchase.mapper.PurchasePlanMapper;
import com.dhecp.project.purchase.mapper.PurchasePlanSonMapper;
import com.dhecp.project.storage.domain.StockAllot;
import com.dhecp.project.storage.domain.StockControl;
import com.dhecp.project.storage.domain.StockControlRunning;
import com.dhecp.project.storage.mapper.StockAllotMapper;
import com.dhecp.project.storage.mapper.StockControlMapper;
import com.dhecp.project.storage.mapper.StockControlRunningMapper;
import com.dhecp.project.storage.service.StockAllotService;
import com.dhecp.project.system.domain.SysUserInfo;
import com.dhecp.project.system.mapper.SysUserInfoMapper;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * @program: kjecp
 * @description: 仓储 库存调拨单
 * @author: hlf
 * @create: 2022-09-01 16:09
 */
@Service
public class StockAllotServiceImpl extends BaseModuleServiceImpl implements StockAllotService {


    @Autowired
    private StockAllotMapper storageMapper;
    @Autowired
    private StockControlMapper stockControlMapper;
    @Autowired
    private OperateCompanyRouteMapper operateCompanyRouteMapper;
    @Autowired
    private StockControlRunningMapper stockControlRunningMapper;
    @Autowired
    private UpdateLogService updateLogService;
    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private PurchaseAddressMapper purchaseAddressMapper;
    @Autowired
    private ModuleNidAndBidMapper moduleNidAndBidMapper;
    @Autowired
    private PurchasePlanMapper purchasePlanMapper;
    @Autowired
    private PurchasePlanSonMapper purchasePlanSonMapper;
    @Autowired
    private ProductActiveMapper productActiveMapper;
    @Autowired
    private SysUserInfoMapper userInfoMapper;
    @Autowired
    private OperateCompanyApplyMapper operateCompanyApplyMapper;

    @Autowired
    private AccountCountForCompanyMapper accountCountForCompanyMapper;

    /**
     * @Description: 查询前一单NID、BID
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: com.dhecp.common.core.domain.AjaxResult  (data.nid 前一单NID， data.bid 前一单BID)
     * @Author: hlf
     * @date: 2022-05-09 10:08
     */
    @Override
    public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        ModuleNID moduleNID = storageMapper.selectLastNid(params);
        if (moduleNID == null) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     * @Description: 查询后一单NID、BID
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: com.dhecp.common.core.domain.AjaxResult  (data.nid 后一单NID， data.bid 后一单BID)
     * @Author: hlf
     * @date: 2022-05-09 10:09
     */
    @Override
    public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        ModuleNID moduleNID = storageMapper.selectNextNid(params);
        if (moduleNID == null) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     * @Description: 查询指定单nid的首记录
     * @Param: [params]
     * @return: com.dhecp.project.storage.domain.StockAllot
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public StockAllot queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return storageMapper.selectFirstRecordByNid(params);
    }

    /**
     * @Description: 查询指定单nid的整单录
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: java.util.List<com.dhecp.project.storage.domain.StockAllot>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<StockAllot> queryListByNid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return storageMapper.selectByNid(params);
    }


    /**
     * @Description: 查询
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.storage.domain.StockAllot>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<StockAllot> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return storageMapper.select(params);
    }

    /**
     * @Description: 保存
     * @Param: [params] moduleTable 必要参数：功能唯一标识
     * @Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @SuppressWarnings("unchecked")
    @Override
    public AjaxResult saveData(Map<String, Object> params) {
        params.put("businessEntity", new StockAllot());

        AjaxResult ajaxResult = this.saveDataBase(params);
        if (!"0".equals(ajaxResult.get("code").toString())) {
            throw new RuntimeException(ajaxResult.get("msg").toString());
        }

        String resNid = "0";
        Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        List<StockAllot> businessDataList = (List<StockAllot>) ajaxResult.get("businessDataList");


        List<RecordCheck> guidMapList = storageMapper.findRecords(infoMap.get("nid").toString());
        Map<String, Object> guidMap = new HashMap<String, Object>();
        if (!guidMapList.isEmpty()) {
            if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())) { //单号重复验证
                throw new RuntimeException(MessageUtils.message("module.error.retry"));
            }
            for (RecordCheck recordCheck : guidMapList) {
                if (recordCheck != null && recordCheck.getGuid() != null) {
                    guidMap.put(recordCheck.getGuid().toString(), "1");
                }
            }
        }

        if (businessDataList == null || businessDataList.size() == 0) {
            resNid = "0";
        } else {
            resNid = infoMap.get("nid").toString();
            for (StockAllot businessData : businessDataList) {
                String guid = "";
                if (businessData.getGuid() == null) {
                    guid = RandomValueUtils.getGUID();
                } else {
                    guid = businessData.getGuid().toString();
                }
                businessData.setGuid(guid);
                for (String field : infoMap.keySet()) { //遍历非网格字段，并赋值到实体中
                    Object fieldValue = infoMap.get(field);
                    ReflectUtils.setValue(businessData, field, fieldValue);
                }
                businessData.setToGoodsArea(businessData.getGoodsArea());
                businessData.setToGoodsAllocation(businessData.getGoodsAllocation());
                businessData.setToWarehouseAddress(businessData.getWarehouseAddress());

                //调入公司
                AccountCountForCompany drCompany = accountCountForCompanyMapper.findByVGsBm(businessData.getToGClient());
                //所属公司
                AccountCountForCompany ssCompany = accountCountForCompanyMapper.findByVGsBm(businessData.getvGsBm());
                //两个的账户类型都为:运营账户
                if (drCompany.getvZhLx().equals("运营账户") && ssCompany.getvZhLx().equals("运营账户")){
                    //查询运营公司备案
                    OperateCompanyApply drOperateCompanyApply = operateCompanyApplyMapper.findVGsBm(businessData.getToGClient());
                    OperateCompanyApply ssOperateCompanyApply = operateCompanyApplyMapper.findVGsBm(businessData.getvGsBm());
                    if (drOperateCompanyApply.getvGsSh() == null || ssOperateCompanyApply.getvGsSh() == null || drOperateCompanyApply.getvGsSh().equals("") || ssOperateCompanyApply.getvGsSh().equals("") ){
                        throw new RuntimeException("公司名称和税号不能为空，请维护!");
                    }
                    //判断:划入公司编码跟划出公司编码的税号是否一致-- 不一致:提醒“非相同税号的公司编码不能进行调拔，请确认!"
                    if (!drOperateCompanyApply.getvGsSh().equals(ssOperateCompanyApply.getvGsSh())){
                        throw new RuntimeException("非相同税号的公司编码不能进行调拔，请确认!");
                    }
                }
                
                businessData.setToVGsJc(drCompany.getvGsJc());
                businessData.setToGCName(drCompany.getvGsMc());

                if (guidMap.get(guid) == null) {
                    businessData.setCreateTime(new Date());
                    storageMapper.insert(businessData);
                    updateLogService.addInsertLog(params.get("moduleTable").toString(), guid, "新增");

                } else {
                    StockAllot oldData;
                    Map<String, Object> params2 = new HashMap<String, Object>();
                    params2.put("guid", guid);
                    oldData = storageMapper.findById(params2);

                    storageMapper.update(businessData);
                    updateLogService.addUpdateLog(params.get("moduleTable").toString(), guid, oldData, businessData, "修改");
                    guidMap.remove(guid);
                }

            }
        }

        if (!guidMap.isEmpty()) {
            for (String guid : guidMap.keySet()) {
                storageMapper.delete(guid);
            }
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), resNid);
    }

    /**
     * @Description: 删除
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult deleteData(Map<String, Object> params) {
        List<StockAllot> businessDataList = JSON.parseArray(params.get("infoItems").toString(), StockAllot.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (StockAllot businessData : businessDataList) {
            storageMapper.delete(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * @Description: 修改删除标志（预留）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串（仅需 guid 和 deleted）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateDeleted(Map<String, Object> params) {
        List<UpdateDeleted> updateDeletedList = JSON.parseArray(params.get("infoItems").toString(), UpdateDeleted.class);
        if (updateDeletedList == null || updateDeletedList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (UpdateDeleted updateDeleted : updateDeletedList) {
            storageMapper.updateDeleted(updateDeleted);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }


    /**
     * @Description: 流转  —— 添加流程任务、修改流程状态及生效标志
     * @Param: [params] tableDataId 必要参数：单据编码（nid）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    @Transactional(timeout = 300, propagation = Propagation.REQUIRES_NEW)//事务回滚
    public AjaxResult updateFlowGo(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack", "单据编码【tableDataId】"));
        } else {
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<StockAllot> businessDataList = storageMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        } else {
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }
        
//        // 判断总数量
//        for (StockAllot businessData : businessDataList) {
//            if (businessData.getActiveFlow().equals("FlowDbQr")) {
//                //获取指定库区的商品
//                Map<String, Object> stock = new HashMap<String, Object>();
//                stock.put("productCode", businessData.getProductCode());
//                stock.put("vGsBm", businessData.getvGsBm());
//                stock.put("gDepot", businessData.getWarehouseAddress());
//                stock.put("vKq", businessData.getGoodsArea());
//                stock.put("vHw", businessData.getGoodsAllocation());
//                Integer sumProductNum = stockControlMapper.sumProductNumByCodeAndHw(stock);
//                if (sumProductNum < businessData.getAllotNum()) {
//                    return AjaxResult.error("库存不足，无法流转!");
//    			}
//    		}
//        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == "") {
            params.put("optType", "go");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);
        try {

            for (StockAllot businessData : businessDataList) {
                if (businessData.getvBz()!= null && businessData.getvBz().equals("1")) {
                    if (updateFlow.getActiveFlow().equals("end")) {//当流程结束时
                        //获取指定库区的商品
                        Map<String, Object> stock = new HashMap<String, Object>();
                        stock.put("productCode", businessData.getProductCode());
                        stock.put("vGsBm", businessData.getvGsBm());
                        stock.put("gDepot", businessData.getWarehouseAddress());
                        stock.put("vKq", businessData.getGoodsArea());
                        stock.put("vHw", businessData.getGoodsAllocation());
                        List<StockControl> stockControls = stockControlMapper.findByCodeAndHw(stock);
                        int alter = 0;
                        if (stockControls.size() > 0) {
                            int num = businessData.getAllotNum();//需要的库存数量
                            for (StockControl item : stockControls
                            ) {
                                if (item.getProductNum() > 0) {
                                    if (num > 0) {
                                        if (num > item.getProductNum()) {
                                            num = num - item.getProductNum();
                                            alter = updateStockControl(businessData, item, item.getProductNum());
                                        } else {
                                            alter = updateStockControl(businessData, item, num);
                                            num = 0;
                                        }
                                    }

                                } else {
                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                    return AjaxResult.error("库存不足!");
                                }
                            }
                        } else {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return AjaxResult.error("库存不足!");
                        }
                        if (alter == 1){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return AjaxResult.error("操作异常!请联系管理员");
                        }
                    }else{//精品调拨 无库存 流转时 生成已完成的采购计划单 -- 0519
                        createPurchasePlan(businessData);
                    }
                }

                updateFlow.setGuid(businessData.getGuid().toString());
                storageMapper.updateFlow(updateFlow);
            }

        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
            return AjaxResult.error("操作失败!");
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }


    /**
     * @Description: 退回  —— 添加流程任务、修改流程状态及生效标志
     * @Param: [params] tableDataId 必要参数：单据编码（nid）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateFlowBack(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack", "单据编码【tableDataId】"));
        } else {
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<StockAllot> businessDataList = storageMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        } else {
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == "") {
            params.put("optType", "back");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (StockAllot businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            storageMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }


    private Integer updateStockControl(StockAllot allot, StockControl item, int num) {
        int alter = 0;
        try {

            //获取公司信息
            OperateCompanyRoute operateCompanyRoute = operateCompanyRouteMapper.findByGsBm(allot.getToGClient());

            //判断是否已存在相同的库存
            Map<String, Object> stocck = new HashMap<>();
            stocck.put("productCode",allot.getProductCode());//商品编码
            stocck.put("vGsBm",operateCompanyRoute.getvGsBm());//所属公司编码
            stocck.put("vHw",allot.getToGoodsAllocation());//货位
            stocck.put("vKq",allot.getGoodsArea());//库区
            stocck.put("gDepot",allot.getToWarehouseAddress());//仓库
            stocck.put("rkGuid",allot.getNid());//仓库
            StockControl newStockControl = stockControlMapper.findByCode2(stocck);


//            //生成新的库存信息
            if (newStockControl != null){
                newStockControl.setProductNum(newStockControl.getProductNum()+num);
                newStockControl.setProductNumAll(newStockControl.getProductNumAll()+num);
                stockControlMapper.update(newStockControl);//生成新的库存信息
            }else{
                newStockControl = new StockControl();
                newStockControl.setGuid(RandomValueUtils.getGUID());
                newStockControl.setProductNum(num);//可用数量
                newStockControl.setProductNumAll(num);//库存总数
                newStockControl.setRkGuid(allot.getNid());//入库标识
                newStockControl.setRkBid(allot.getBid());//入库单号
                newStockControl.setIsParent("1");//是否母件
                newStockControl.setvHw(allot.getToGoodsAllocation());//入库货位
                newStockControl.setvKq(allot.getGoodsArea());//库区
                newStockControl.setgDepot(allot.getToWarehouseAddress());//所在仓库
                newStockControl.setvGsBm(operateCompanyRoute.getvGsBm());//公司编码
                newStockControl.setvGsJc(operateCompanyRoute.getvGsJc());//公司简称
                newStockControl.setvGsMc(operateCompanyRoute.getvGsMc());//公司名称
                newStockControl.setProductCode(allot.getProductCode());//商品编码
                newStockControl.setProductName(allot.getProductName());
                ;//商品名称
                newStockControl.setPurchasePrice(allot.getPrice());//商品采购价
                newStockControl.setPurchaseTotalPriceAll(allot.getTotalPrice());//采购总价
                newStockControl.setAllotPrice(0.00);//调拨单价
                newStockControl.setTotalAllotPrice(0.00);//调拨总价
                newStockControl.setsDays(0);//库存天数
                newStockControl.setPurchaseStorageID("");//采购入库单
                newStockControl.setPurchaseOrderID("");//采购订单
                newStockControl.setPurchasePlanID("");//采购计划单
                newStockControl.setdRkSj(new Date());//入库日期
                newStockControl.setCreateTime(new Date());//创建日期
                stockControlMapper.insert(newStockControl);//生成新的库存信息


            }
            // 新库存添加库存流水
            StockControlRunning stockControlRunning = new StockControlRunning();
            stockControlRunning.setGuid(RandomValueUtils.getGUID());
            stockControlRunning.setGuidStockControl(newStockControl.getGuid());
            stockControlRunning.setBidRelative(allot.getBid());
            stockControlRunning.setLocationHw(newStockControl.getvHw());
            stockControlRunning.setProductCode(newStockControl.getProductCode());
            stockControlRunning.setvGsBm(newStockControl.getvGsBm());
            stockControlRunning.setProductNumChange(num);
            stockControlRunning.setProductNumLeft(num);
            stockControlRunning.setCreateTime(new Date());
            stockControlRunning.setRemark("库存调拨单 - 调入方 " + allot.getBid());
            stockControlRunningMapper.insert(stockControlRunning);



            //修改旧的库存信息
            item.setProductNumAll(item.getProductNumAll() - num);
            item.setProductNum(item.getProductNum() - num);
            stockControlMapper.update(item);

            // 旧库存添加库存流水
            StockControlRunning stockControlRunning2 = new StockControlRunning();
            stockControlRunning2.setGuid(RandomValueUtils.getGUID());
            stockControlRunning2.setGuidStockControl(item.getGuid());
            stockControlRunning2.setBidRelative(allot.getBid());
            stockControlRunning2.setLocationHw(item.getvHw());
            stockControlRunning2.setProductCode(item.getProductCode());
            stockControlRunning2.setvGsBm(item.getvGsBm());
            stockControlRunning2.setProductNumChange(num);
            stockControlRunning2.setProductNumLeft(item.getProductNumAll());
            stockControlRunning2.setCreateTime(new Date());
            stockControlRunning2.setRemark("库存调拨单 - 调出方 " + allot.getBid());
            stockControlRunningMapper.insert(stockControlRunning2);

        } catch (Exception ex) {
            alter = 1;
        }
        return alter;
    }


    //生成采购计划
    public void createPurchasePlan(StockAllot stockAllot) {
//        ChoiceShop choiceShop, Integer allot, OperateCompanyApply corporate

        PurchasePlan plan = new PurchasePlan();

        //获取商品信息
        ProductActive productActive = productActiveMapper.findProductActiveByCode(stockAllot.getProductCode());

        //获取商品子件信息
        ProductActiveComponent productActiveComponent = productActiveMapper.findFirstProductActiveComponentByPcode(stockAllot.getProductCode());
        //获取所属公司信息
        OperateCompanyApply corporate2 = operateCompanyApplyMapper.findVGsBm("GS0641");

        SysUserInfo sysUserInfo = userInfoMapper.findByUserId(corporate2.getcUser());


        Map<String, Object> params = new HashMap<>();
        params.put("moduleTable", "TCG_PURCHASEPLAN");
        //有事务控制，制单异常不跳过单号
        ModuleNidAndBid moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params);
        PurchaseAddress purchaseAddress = purchaseAddressMapper.getTop1();


        double cost = 0.00;//订单总金额
        try {
            //生成采购计划 母件 信息
            //基础信息
            plan.setNid(moduleNidAndBid.getNid());
            plan.setBid(moduleNidAndBid.getBid());
            plan.setCreateTime(new Date());
            plan.setCid(sysUserInfo.getCid());
            plan.setCidName(sysUserInfo.getCidName());
            plan.setbUser(sysUserInfo.getUserId());
            plan.setbUserName(sysUserInfo.getUserName());
            plan.setbDept(sysUserInfo.getDeptId());
            plan.setbDeptName(sysUserInfo.getDeptName());
            plan.setbPosition(sysUserInfo.getPositionName());
            plan.setaUser(sysUserInfo.getUserId());
            plan.setaUserName(sysUserInfo.getUserName());
            plan.setaDept(sysUserInfo.getDeptPath());
            plan.setaDeptName(sysUserInfo.getDeptName());
            plan.setaPosition(sysUserInfo.getPositionName());
            plan.setvGsDz(purchaseAddress.getAddress());//获取默认地址
            plan.setAddressId(purchaseAddress.getGuid());//地址标识
            plan.setEffectStock(true);//是否生效
            plan.setDeleted(false);//是否删除
            plan.setActiveFlow("end");//流程状态
            plan.setvZdbz("逸思精品调拨");//单据备注

            //母件信息
            plan.setSpBm(stockAllot.getProductCode());//商品编码
            plan.setSpSl(stockAllot.getAllotNum());//采购数量
            plan.setvType(2);//商品编码
            plan.setSort("线下");//类型 (线上/线下
            plan.setIsJp("是");//类型 (线上/线下
//            plan.setOrderState("订单已生成");//订单状态 (订单已生成/空/订单已删除
            plan.setvGsBm(stockAllot.getvGsBm());
            plan.setvGsJc(stockAllot.getvGsJc());
            plan.setvGsMc(stockAllot.getvGsMc());

            //订单地址
            Map<String, Object> address = new HashMap<String, Object>();
            address.put("guid", plan.getAddressId());
            PurchaseAddress purchaseAddress2 = purchaseAddressMapper.findById(address);
            if (purchaseAddress2 != null) {
                plan.setPhone(purchaseAddress2.getPhone());//联系电话
                plan.setvBank(purchaseAddress2.getvBank());//开户行
                plan.setvAccount(purchaseAddress2.getvAccount());//银行账号
                plan.setvTax(purchaseAddress2.getvTax());//税号
                plan.setvJydz(purchaseAddress2.getvJydz());//经营地址
                plan.setvKpdh(purchaseAddress2.getvKpdh());//开票电话
                plan.setvKpdz(purchaseAddress2.getvKpdz());//开票地址
                plan.setvGsfr(purchaseAddress2.getvGsfr());//公司法人
                plan.setvLxdh(purchaseAddress2.getvLxdh());//联系电话
                plan.setvFax(purchaseAddress2.getvFax());//传真
                plan.setvGjH(purchaseAddress2.getvGjH());//所在国家
                plan.setvSfH(purchaseAddress2.getvSfH());//省份
                plan.setvDsH(purchaseAddress2.getvDsH());//城市
                plan.setvCqH(purchaseAddress2.getvCqH());//城区
                plan.setvDzH(purchaseAddress2.getvDzH());//街道
                plan.setvYbH(purchaseAddress2.getvYbH());//邮编
                plan.setvFhr(purchaseAddress2.getvFhr());//发货人
                plan.setvFhrSj(purchaseAddress2.getvFhrSj());//发货人手机
                plan.setvFhrDh(purchaseAddress2.getvFhrDh());//发货人电话
                plan.setvGjP(purchaseAddress2.getvGjP());//国家 票
                plan.setvSfP(purchaseAddress2.getvSfP());//省份 票
                plan.setvDsP(purchaseAddress2.getvDsP());//城市 票
                plan.setvCqP(purchaseAddress2.getvCqP());//城区 票
                plan.setvDzP(purchaseAddress2.getvDzP());//地址 票
                plan.setvYbP(purchaseAddress2.getvYbP());//邮编 票
                plan.setvSpr(purchaseAddress2.getvSpr());//收票人
                plan.setvSprSj(purchaseAddress2.getvSprSj());//收票人手机
                plan.setvSprDh(purchaseAddress2.getvSprDh());//收票人电话
                plan.setInvoiceType(purchaseAddress2.getInvoiceType());//发票类型
            }
            //生成子件数据
            List<PurchasePlanSon> sonList = purchasePlanSonMapper.queryListFbm(plan.getSpBm());
            Integer xb = 0;
            for (PurchasePlanSon item : sonList
            ) {
                if (item.getfBm().equals(plan.getSpBm())) {
                    xb++;
                    item.setGuid(RandomValueUtils.getGUID());
                    item.setCreateTime(new Date());
                    item.setfNid(plan.getNid());
                    item.setfBm(plan.getSpBm());//父商品编码
                    item.setCgSl((int) Math.round(stockAllot.getAllotNum() * item.getNum()));//母件计划子件采购数量
                    item.setJgSl(0);//子件加购数量
                    item.setPrices(productActiveComponent.getbPrice()); // 子件预估单价
                    item.setTotalPrices(productActiveComponent.getbPrice() * item.getCgSl());//子件预估总价
                    item.setAllNum((int) Math.round(stockAllot.getAllotNum() * item.getNum()));//子件总数
                    item.setpGuid(plan.getGuid());//父标识
                    item.setIid(xb);//行号
                    cost = cost + item.getTotalPrices();
                    purchasePlanSonMapper.insert(item);
                }

            }
            plan.setPlanCost(cost);
            plan.setUpdateTime(new Date());
            purchasePlanMapper.insert(plan);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }

    }

}